/**
 * HttpRequest.java
 * com.tencent.common
 * Copyright (c) 2015, 北京 快先生科技有限公司版权所有.
*/

package com.sftz.modules.minapp.pay.util;

import java.net.SocketTimeoutException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class HttpRequest {

	private static Log log = Logs.get();

	public static String sendPost(String url, Map<String, Object> parameters) {

		String result = null;

		HttpPost httpPost = new HttpPost(url);

		//将要提交给API的数据对象转换成XML格式数据Post给API
		String postDataXML = PayCommonUtil.getRequestXml(parameters);

		log.debug("API，POST过去的数据是：");
		log.debug(postDataXML);

		//得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
		StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
		httpPost.addHeader("Content-Type", "text/xml");
		httpPost.setEntity(postEntity);

		log.debug("executing request" + httpPost.getRequestLine());

		try {
			//非ssl连接
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpResponse response = httpClient.execute(httpPost);

			HttpEntity entity = response.getEntity();

			result = EntityUtils.toString(entity, "UTF-8");

		} catch (ConnectionPoolTimeoutException e) {
			log.error("http get throw ConnectionPoolTimeoutException(wait time out)");

		} catch (ConnectTimeoutException e) {
			log.error("http get throw ConnectTimeoutException");

		} catch (SocketTimeoutException e) {
			log.error("http get throw SocketTimeoutException");

		} catch (Exception e) {
			log.error("http get throw Exception");

		} finally {
			httpPost.abort();
		}

		return result;
	}

}
